package top.oneit.jdownload.controller.component;

import cn.hutool.core.util.IdUtil;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import top.oneit.jdownload.utils.XmlUtils;

import java.net.URL;
import java.util.ResourceBundle;

public class HeaderItemController implements Initializable {
    @FXML
    private HBox headerHBox;
    @FXML
    private TextField key;
    @FXML
    private TextField value;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        String simpleUUID = IdUtil.objectId();
        headerHBox.setId("headerHBox" + simpleUUID);
        Button del = (Button) headerHBox.lookup("#del");
        Button add = (Button) headerHBox.lookup("#add");
        add.setId("add" + simpleUUID);
        del.setId("del" + simpleUUID);
        add.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Pane parent = (Pane) add.getParent().getParent();
                int index = 1;
                for (Node node : parent.getChildren()) {
                    if (node.getId().equals(add.getParent().getId())) {
                        break;
                    }
                    index++;
                }
                HBox load = XmlUtils.loadXML("/fxml/dialog/component/header-item.fxml");
                parent.getChildren().add(index, load);
            }
        });
        del.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Pane parent = (Pane) del.getParent().getParent();
                parent.getChildren().remove(del.getParent());
            }
        });
    }

}
